package com.sinbader.xiaole.appapi.service;

import cn.stylefeng.guns.sys.core.auth.AuthServiceImpl;
import cn.stylefeng.guns.sys.core.constant.state.ManagerStatus;
import cn.stylefeng.guns.sys.modular.enums.UserTypes;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.mapper.UserMapper;
import com.sinbader.xiaole.common.model.params.WxUserInfoParams;
import org.apache.xmlbeans.UserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WxLoginService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private AuthServiceImpl authService;

	public String login(WxUserInfoParams userInfoParams) {
		User user = userMapper.getByWxUnionId(userInfoParams.getUnionId());
		if(user == null) {
			user = new User()
					.setWxUnionId(userInfoParams.getUnionId())
					.setNickName(userInfoParams.getNickName())
					.setAvatar(userInfoParams.getAvatar())
					.setStatus(ManagerStatus.OK.getCode())
					.setType(UserTypes.Common)
					.setCreateTime(new Date());
			userMapper.insert(user);
		} else {
			user.setNickName(userInfoParams.getNickName());
			user.setAvatar(userInfoParams.getAvatar());
			userMapper.updateById(user);
		}
		String token = authService.login(user);
		return token;
	}

}
